package com.vhall.component.controller.interactive;

import cn.hutool.core.bean.BeanUtil;
import com.vhall.component.controller.interactive.facade.DocumentConsoleFacade;
import com.vhall.component.entity.interactive.vo.*;
import com.vhall.component.framework.common.annotation.VhallComponent;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.annotation.TokenAuth;
import com.vhall.component.plugin.common.enums.OperateTypeEnum;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.service.annotation.OperateLog;
import com.vhall.component.service.interactive.DocumentsConsoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


/**
 * @author shenqing
 * @date 2021/4/27 11:14
 */
@Slf4j
@VhallComponent
@TokenAuth
public class DocumentConsoleController implements DocumentConsoleFacade {
    @Autowired
    private DocumentsConsoleService documentsConsoleService;

    @Override
    @OperateLog(type = OperateTypeEnum.IMPORT, name = "文档上传")
    public Boolean consoleUpload(DocumentConsoleUploadReqVO reqVO) {
        return documentsConsoleService.consoleUpload(reqVO);
    }

    @Override
    public DocumentDeleteRespVO delete(DocumentConsoleDeleteReqVO reqVO) {
        return documentsConsoleService.delete(reqVO);
    }

    @Override
    public DocumentConsoleListRspVO list(DocumentConsoleListReqVO reqVO) {
        DocumentListRspVO source = documentsConsoleService.list(reqVO);
        DocumentConsoleListRspVO result = new DocumentConsoleListRspVO();
        if (source != null) {
            BeanUtil.copyProperties(source, result);
            result.setData(source.getDetail());
        }
        return result;
    }

    public DocumentUploadLargeFileRespVO consoleUploadLargeFile(HttpServletRequest request, DocumentUploadLargeFileReqVO reqVO) {
        try {
            DocumentUploadLargeFileRespVO fileRespVO = new DocumentUploadLargeFileRespVO();
            boolean isMutipart = ServletFileUpload.isMultipartContent(request);
            if (isMutipart) {
                MultipartFile file = reqVO.getFile();

                if (file == null) {
                    throw new BusinessException(BizErrorCode.COMP_DOC_EMPTY);
                }

                File outFile = new File(generatePath(reqVO));
                InputStream inputStream = file.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, outFile);

                //判断所有分片是否全部上传完成，完成就合并
                File dir = new File(getnerateFileDir(reqVO));
                File[] files = dir.listFiles();
                if (files.length == reqVO.getTotalChunks()) {
                    //合并文件
                    String filePath = mergeFile(reqVO);
                    fileRespVO.setRelativePath(filePath);
                    return fileRespVO;
                }

            }
            return fileRespVO;
        } catch (Exception e) {
            throw new BusinessException(BizErrorCode.BIZ_UPLOAD_FAILED);
        }

    }

    /**
     * 获取上传文件路径
     */
    public String generatePath(DocumentUploadLargeFileReqVO reqVO) {
        StringBuilder sb = new StringBuilder();
        String uploadDir = "";
        sb.append(uploadDir).append("/").append(reqVO.getIdentifier());
        if (!Files.isWritable(Paths.get(sb.toString()))) {
            log.info("path not exist, create path:", sb.toString());
        }
        try {
            Files.createDirectories(Paths.get(sb.toString()));
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return sb.append("/").append(reqVO.getFilename()).append("-").append(reqVO.getChunkNumber().toString()).toString();
    }


    /**
     * 获取切片路径
     */
    public String getnerateFileDir(DocumentUploadLargeFileReqVO reqVO) {
        StringBuilder sb = new StringBuilder();
        String uploadDir = "";
        sb.append(uploadDir).append("/").append(reqVO.getIdentifier());
        return sb.toString();
    }

    /**
     * 合并文件
     */
    public String mergeFile(DocumentUploadLargeFileReqVO reqVO) {
        String filename = reqVO.getFilename();
        //文件路径
        String folder = getnerateFileDir(reqVO);
        //生成文件名
        String file = folder + File.separator + filename;
        //合并
        merge(file, folder);
        //返回相对路径
        return reqVO.getIdentifier() + File.separator + filename;
    }

    /**
     * 合并
     */
    public void merge(String targetFile, String folder) {
        try {
            Files.createFile(Paths.get(targetFile));
            Files.list(Paths.get(folder))
                    .filter(path -> path.getFileName().toString().contains("-"))
                    .sorted((o1, o2) -> {
                        String p1 = o1.getFileName().toString();
                        String p2 = o2.getFileName().toString();
                        int i1 = p1.lastIndexOf("-");
                        int i2 = p2.lastIndexOf("-");
                        return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
                    })
                    .forEach(path -> {
                        try {
                            //以追加的形式写入文件
                            Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
                            //合并后删除该块
                            Files.delete(path);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
